<template>
  <div class="app-container cycle-outer-wrapper">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="类别" prop="categoryName">
        <el-input v-model="queryParams.categoryName" placeholder="请输入类别" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:cycle:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="cycleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="类别名称" align="center" prop="categoryName" />
      <el-table-column label="开始时间" align="center" prop="startTime" />
      <el-table-column label="检测周期" align="center" prop="frequency">
        <template slot-scope="{ row }">
          {{ `${row.days}${row.tianyue === 1 ? "天" : "月"}` }}
        </template>
      </el-table-column>
      <el-table-column label="检测频次" align="center" prop="frequency" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:cycle:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:cycle:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入类别" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
            @change="handleChangeTime"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检测周期" prop="days">
          <el-row>
            <el-col :span="18">
              <el-input-number
                placeholder="请输入"
                style="width: 100%"
                v-model="form.days"
                class="input-with-select cycle-input"
                :min="1"
                :controls="false"
                :max="100"
              >
              </el-input-number>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="tianyue"
                class="cycle-select"
                @change="handleChangeTianyue"
              >
                <el-option label="天" :value="1"></el-option>
                <el-option label="月" :value="2"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="检测频次" prop="frequency">
          <el-input-number
            v-model="frequency"
            @change="handleChangesss"
            :min="1"
            :max="366"
            label="描述文字"
            style="width: 77.5%"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCycle,
  getCycle,
  delCycle,
  addCycle,
  updateCycle,
  exportCycle,
} from "@/api/control/cycle";

export default {
  name: "Cycle",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      cycleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: null,
        cycleId: null,
      },
      // 表单参数
      form: {
        tianyue: 1,
      },
      tianyue: 1,
      frequency: 1,
      // 表单校验
      rules: {
        categoryName: [
          {
            required: true,
            message: "请输入类别名称",
          },
        ],
        startTime: [
          {
            required: true,
            message: "请选择开始时间",
          },
        ],
        days: [
          {
            required: true,
            message: "请输入检测周期",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleChangeTianyue(val) {
      console.log(val);
      if (val === 2 && this.form.startTime) {
        this.form.startTime = this.getCurrentMonthFirst(this.form.startTime);
      }
    },
    handleChangeTime() {
      if (this.tianyue === 2) {
        this.handleChangeTianyue(2);
      }
    },
    // 获取月份第一天
    getCurrentMonthFirst(date) {
      var date = new Date(date);
      date.setDate(1);
      var month = parseInt(date.getMonth() + 1);
      var day = date.getDate();
      if (month < 10) {
        undefined;
        month = "0" + month;
      }
      if (day < 10) {
        undefined;
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + day;
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listCycle(this.queryParams).then((response) => {
        this.cycleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.frequency = 1;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        categoryId: null,
        cycleId: null,
      };
      this.frequency = 1;
      this.tianyue = 1;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.detectionName = this.days + "天" + "/" + this.frequency + "次";
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCycle(id).then((response) => {
        this.form = response.data;
        this.tianyue = response.data.tianyue;
        this.days = response.data.days;
        this.frequency = response.data.frequency;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.tianyue = this.tianyue;
          if (this.form.id != null) {
            if (
              this.form.categoryName == "" ||
              this.form.categoryName == null
            ) {
              this.msgError("类别不能为空！");
              return false;
            }
            if (this.form.days < this.frequency && this.tianyue !== 2) {
              this.msgError("检测周期不能小于检测次数！");
              return false;
            }
            this.form.frequency = this.frequency;
            updateCycle(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.frequency = 1;
              this.queryParams.pageNum = 1;
              this.getList();
            });
          } else {
            if (
              this.form.categoryName == "" ||
              this.form.categoryName == null
            ) {
              this.msgError("类别不能为空！");
              return false;
            }
            if (this.form.days < this.frequency && this.tianyue !== 2) {
              this.msgError("检测周期不能小于检测次数！");
              return false;
            }
            this.form.frequency = this.frequency;
            addCycle(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.frequency = 1;
              this.open = false;
              this.queryParams.pageNum = 1;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("是否确认删除?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delCycle(ids);
        })
        .then(() => {
          this.queryParams.pageNum = 1;
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有【请填写功能名称】数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportCycle(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    handleChange(value) {
      this.form.detectionName = value + "天" + "/" + this.frequency + "次";
    },
    handleChangesss(value) {
      this.form.detectionName = this.form.days + "天" + "/" + value + "次";
    },
  },
};
</script>
<style scoped>
/* /deep/ .el-input--medium .el-input__inner {
  width: 240px;
} */
</style>
<style>
/* .cycle-input .el-input .el-input__inner {
  width: 160px;
}
.cycle-select .el-input .el-input__inner {
  width: 100%;
  box-sizing: border-box;
} */
</style>
